<template>
  <section class="py-12 bg-neutral min-h-screen">
    <div class="container mx-auto px-4">
      <!-- 页面标题 -->
      <div class="text-center mb-10">
        <h2 class="text-[clamp(1.5rem,3vw,2.5rem)] font-bold mb-4">{{ work?.title || '作品详情' }}</h2>
        <p class="text-gray-600 max-w-2xl mx-auto">
          {{ work?.created }} · {{ work?.style }}风格 · {{ work?.tone }}基调
        </p>
      </div>
      
      <!-- 作品内容 -->
      <div v-if="work" class="bg-white rounded-xl shadow-sm p-6 mb-8">
        <!-- 作品文本 -->
        <div class="mb-8">
          <h3 class="text-lg font-semibold mb-3">作品内容</h3>
          <p class="text-gray-700 whitespace-pre-wrap">{{ work.text }}</p>
        </div>
        
        <!-- 分镜列表 -->
        <div>
          <h3 class="text-lg font-semibold mb-4">分镜展示</h3>
          <div v-if="work.frames && work.frames.length > 0" class="space-y-8">
            <div 
              v-for="(frame, index) in work.frames" 
              :key="index"
              class="border border-gray-200 rounded-lg overflow-hidden hover:shadow-md transition-shadow"
            >
              <div class="p-4 bg-gray-50 border-b border-gray-200">
                <h4 class="font-medium">分镜 {{ index + 1 }}</h4>
                <p class="text-gray-600 text-sm mt-1">{{ frame.desc }}</p>
              </div>
              <div class="p-4 flex justify-center">
                <img 
                  :src="frame.url" 
                  :alt="`分镜 ${index + 1}`"
                  class="max-w-full h-auto max-h-[500px] object-contain"
                >
              </div>
              <div class="p-4 bg-gray-50 border-t border-gray-200 flex justify-end">
                <button 
                  class="px-4 py-2 bg-primary/10 text-primary rounded hover:bg-primary/20 transition-colors text-sm"
                  @click="downloadFrame(frame.url, index)"
                >
                  <i class="fa fa-download mr-1"></i> 下载分镜
                </button>
              </div>
            </div>
          </div>
          <div v-else class="text-center py-8 text-gray-500">
            暂无分镜数据
          </div>
        </div>
      </div>
      
      <!-- 未找到作品状态 -->
      <div v-else class="text-center py-16 bg-white rounded-xl shadow-sm">
        <svg class="w-16 h-16 text-gray-400 mx-auto mb-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"></path>
        </svg>
        <h3 class="text-xl font-medium text-gray-500 mb-2">未找到作品</h3>
      </div>
      
      <!-- 返回按钮 -->
      <div class="text-center">
        <button 
          class="px-6 py-3 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
          @click="$router.push('/my-works')"
        >
          <i class="fa fa-arrow-left mr-2"></i> 返回作品集
        </button>
      </div>
    </div>
  </section>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'

// 路由参数
const route = useRoute()
const workId = parseInt(route.params.id)

// 响应式数据
const work = ref(null)

// 处理图片URL，确保正确移除反引号和空格
const processImageUrl = (url) => {
  if (!url || typeof url !== 'string') {
    return '/vite.svg'
  }
  // 移除所有引号（单引号、双引号、反引号）和空白字符
  return url.replace(/[`'"\s]/g, '').trim() || '/vite.svg'
}

// 下载单个分镜
const downloadFrame = (frameUrl, index) => {
  if (!frameUrl || frameUrl === '/vite.svg') {
    alert('无法下载图片：图片URL无效')
    return
  }
  
  try {
    // 创建下载链接
    const link = document.createElement('a')
    link.href = frameUrl
    link.download = `frame-${workId}-${index + 1}.jpg`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  } catch (error) {
    console.error('下载图片失败:', error)
    alert('下载失败，请稍后重试')
  }
}

// 从本地存储或路由状态中获取作品数据
onMounted(() => {
  // 尝试从window对象中获取所有作品数据
  if (window.allWorks && Array.isArray(window.allWorks)) {
    // 关键修复：使用精确的字符串比较，因为ID可能不是数字类型
    // 先将workId转换为字符串，然后与item.Uid进行字符串比较
    const workIdStr = String(workId);
    
    // 遍历查找匹配的作品
    let foundWork = null;
    for (let i = 0; i < window.allWorks.length; i++) {
      const item = window.allWorks[i];
      // 尝试多种方式匹配ID
      if (String(item.Uid) === workIdStr || String(item.id) === workIdStr) {
        foundWork = item;
        break;
      }
    }
    
    if (foundWork) {
      // 转换数据格式，处理分镜URL
      work.value = {
        id: foundWork.Uid || foundWork.id,
        title: (foundWork.Text || '').substring(0, 20) + (foundWork.Text && foundWork.Text.length > 20 ? '...' : ''),
        text: foundWork.Text || '',
        created: foundWork.Ctime ? new Date(foundWork.Ctime * 1000).toISOString().split('T')[0] : new Date().toISOString().split('T')[0],
        style: foundWork.Style || '未知风格',
        tone: foundWork.Tone || '未知基调',
        frames: foundWork.Draws && Array.isArray(foundWork.Draws) 
          ? foundWork.Draws.map((draw, index) => ({
              id: index + 1,
              desc: draw.Desc || `分镜 ${index + 1}`,
              url: processImageUrl(draw.Url)
            }))
          : []
      }
    }
  }
})
</script>